import os
from typing import Optional

from pydantic import Field, MongoDsn, PostgresDsn, RedisDsn
from pydantic_settings import BaseSettings, SettingsConfigDict

from fastapi_template.consts import ENV_PREFIX

TARGET = os.environ.get("TARGET", "dev")  # dev, test, prod
env_file_path = os.environ.get("ENV_FILE_PATH") or ".env"
print("use env file: %s" % env_file_path)


class ServiceConfig(BaseSettings):
    model_config = SettingsConfigDict(
        env_prefix=ENV_PREFIX,
        case_sensitive=False,
        env_file=env_file_path,
        extra="ignore",
    )

    ENV: str = Field(TARGET, description="dev, test, prod")

    DEFAULT_MONGO_URI: MongoDsn = Field(
        ..., description="mongodb://user:password@ip:port")
    DEFAULT_MONGO_DBNAME: str = Field(..., description="default db name")
    POSTGRES_DSN: Optional[PostgresDsn] = Field(
        None,
        description="postgresql://user:password@ip:port/db",
    )

    REDIS_DSN: RedisDsn = Field(...)
    IS_SAFE_ENV: bool = Field(TARGET in ["dev", "test"])

    JWT_NAME: str = "PR_TOKEN" if TARGET == "prod" else "PR_TOKEN_TEST"
    JWT_SECRET: str = "JWT_SECRET"
    JWT_ALGORITHM: str = "HS256"
    JWT_MAX_AGE: int = 86400 * 30 - 3600 * 1

    CACHE_NAMESPACE: str = "fst"
    CACHE_DB: int = 0
    USE_CACHE_NAME: str = "redis"


app_config = ServiceConfig()  # type: ignore

print("TARGET: {}; DB: {}".format(
    app_config.ENV,
    app_config.DEFAULT_MONGO_DBNAME,
))


def _test_config():
    from pprint import pprint

    pprint(app_config.model_dump())
    pass


if __name__ == "__main__":
    _test_config()
